package scholarsearch.activity;



import java.util.ArrayList;

import scholarsearch.android.IndexSearch;
import scholarsearch.android.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class Main extends Activity {
	private RadioButton autoriRadioButton;
	private CheckBox avanzata;
	private String nomeAutore=new String();
	private EditText autoreEditText;
	private IndexSearch ricerca = new IndexSearch();
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
       
        // STANZIAMENTO RADIOBUTTON
        autoriRadioButton=(RadioButton) findViewById(R.id.radioPiu);
        autoriRadioButton.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if ( isChecked )
                {
                Context context = getBaseContext();
            	  Intent myIntent = new Intent(context, RicercaPiuAutori.class);
                startActivityForResult(myIntent, 0);
                finish();
                }

            }
        });
        
        // STANZIAMENTO CHECKBOX
        avanzata=(CheckBox) findViewById(R.id.checkBoxRicercaAvanzata);
        avanzata.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if ( isChecked==true )
                {
                Context context = getBaseContext();
            	  Intent myIntent = new Intent(context, RicercaAvanzata.class);
                startActivityForResult(myIntent, 0);
                finish();
                }
			}
        });
        
        // STANZAIMENTO EDITTEXT
        autoreEditText = (EditText) findViewById(R.id.editTextAutore);
    }
    
    /**
     * Metodo di controllo connessione, controlla sia presente una connessione internet
     * 
     * @return null
     */
    private boolean CheckIntConn() {
        ConnectivityManager connectivityManager
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
    
    /**
     * Metodo di gestione del pulsante Cerca, verifica vi siano parametri utili per la ricerca e, in caso di presenza di una connessione internet, inizializza la ricerca
     * 
     * @param v, View
     * 
     *         Riferimento al button premuto
     */
    public void ricercaSemplice(View v) {
    	nomeAutore=ricerca.verificaStringa(autoreEditText.getText().toString());
   		boolean checkConnection=false;
   		if (nomeAutore.contains("#vuoto#")==false){
	   		if(CheckIntConn()){
	            Context context = getApplicationContext();
	            checkConnection=true;
	         }
	   		else{
	    	    checkConnection=false;
	            Context context = getApplicationContext();
	            CharSequence text = "Connessione non attiva";
	            int duration = Toast.LENGTH_SHORT;
	            Toast toast = Toast.makeText(context, text, duration);
	            toast.show();
	         }
	   		if (checkConnection==true){
	   			
	   			
	   			ArrayList<String> autori= new ArrayList<String>();
	   			autori.add(nomeAutore);
	   			Intent intent = new Intent(getApplicationContext(), RisultatiRicerca.class);
	   			String pkg=getPackageName();
	   			intent.putStringArrayListExtra(pkg+".nomiAutori", autori);
	   			intent.putExtra(pkg+".URL", ricerca.ricercaSemplice(nomeAutore));
	   			ArrayList<String> materie= new ArrayList<String>();
				materie.add("Tutte le materie");
	   			intent.putStringArrayListExtra(pkg+".materieRicerca", materie);
	   			intent.putExtra(pkg+".tipoRicerca", "Ricerca ovunque");
	            startActivity(intent);
	            }
	   		}
   		else {
            Toast toast = Toast.makeText(getApplicationContext(), "Valori di ricerca errati", Toast.LENGTH_SHORT);
            toast.show();
   		}
	}
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
}
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.nuova_ricerca:
        	//Toast.makeText(this.getApplicationContext(),"Nuova ricerca",Toast.LENGTH_SHORT).show();
        	Context context = getBaseContext();
      	    Intent myIntent = new Intent(context, Main.class);
            startActivityForResult(myIntent, 0);
            finish();
            return true;
        case R.id.carica_ricerca:
        	Context contextCarica = getBaseContext();
      	    Intent myIntentCarica = new Intent(contextCarica, Carica.class);
            startActivityForResult(myIntentCarica, 0);
        	return true;
        case R.id.info:
        	Toast.makeText(this.getApplicationContext(),"Info",Toast.LENGTH_SHORT).show();
            return true;
        case R.id.chiudi:
        	finish();
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}
